package com.yuandian.bpm.bi.modules.customs.sevice.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yuandian.bpm.bi.modules.customs.mapper.CustomerReportMapper;
import com.yuandian.bpm.bi.modules.customs.sevice.CustomReportService;
import com.yuandian.bpm.bi.modules.quartz.vo.ConfReportTaskInfo;
import com.yuandian.bpm.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.jeecg.modules.jmreport.desreport.entity.JimuReport;
import org.jeecg.modules.jmreport.desreport.entity.JimuReportShare;
import org.jeecg.modules.jmreport.desreport.model.QueryVO;
import org.jeecg.modules.jmreport.desreport.service.IJimuReportService;
import org.jeecg.modules.jmreport.desreport.service.IJimuReportShareService;
import org.jeecg.modules.jmreport.desreport.service.IJmReportExportExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CustomServiceImpl implements CustomReportService {

	@Autowired
	private IJmReportExportExcel exportExcel;
	@Autowired
	private IJimuReportService jmReportDesignService;
	@Autowired
	private CustomerReportMapper customerReportMapper;
	@Autowired
	private IJimuReportShareService jurisdictionService;
	/**
	 * 当前应用程序，启动目录
	 */
	private final String user_path = "user.dir";
	/**
	 * 文档生成存放路径名称
	 */
	private final String doc_path = "docs";
	/**
	 * 文档生成存放基础路径
	 */
	private final String basePath = System.getProperty(user_path) + File.separator + doc_path;


	/**
	 * excel导出
	 *
	 * @param json    参数对象,queryParam里面
	 */
	@Override
	public String exportAllExcelStream(JSONObject json) {
		String reportId = json.getString("excelConfigId");
		JSONObject param = json.getJSONObject("queryParam");
		//1、调用参数查询接口查询配置了哪些条件或者自己查表
		// SELECT * from jimu_report_db_param where jimu_report_head_id in (SELECT id from jimu_report_db where jimu_report_id='828132922182660096');
		//查询配置信息
		List<QueryVO> queryVOS = this.jmReportDesignService.getReportQueryInfo(reportId, param.toJSONString());
		Map<String, String> collect = queryVOS.stream().collect(Collectors.toMap(QueryVO::getName, QueryVO::getDefaultValue, (key1, key2) -> key2));
		JSONObject jsonObject = BeanUtil.toBean(collect, JSONObject.class);
		setParamValue(jsonObject, json.getJSONObject("queryParam"));
		long startTime = System.currentTimeMillis();
		JSONArray base64Arry = json.getJSONArray("base64Arry");//excel中有图表时用到
		//2、调用导出方法导出excel
		log.info("===========exportAllExcelStream 执行导出EXCEL action ==========");
		Map excelInfoMap = this.exportExcel.exportExcel(reportId, jsonObject, base64Arry);
		checkDocsBasePathAndTmpDocs();
		JimuReport report = this.jmReportDesignService.getById(reportId);
		String filePath = basePath + File.separator + report.getName() + DateUtil.today() + ".xlsx";
		String fileName = json.getString("fileName");
		//如果定时任务配置的文件名不为空，则取定时任务的文件名配置
		if (ObjectUtil.isNotEmpty(fileName)) {
			filePath = basePath + File.separator + fileName + "_" + DateUtil.today() + ".xlsx";
		}
		try (BufferedOutputStream outputStream = FileUtil.getOutputStream(filePath);
			 SXSSFWorkbook sxssfWorkbook = (SXSSFWorkbook) excelInfoMap.get("workbook")) {
			sxssfWorkbook.write(outputStream);
			outputStream.flush();
		} catch (IOException e) {
			log.error("excel写出异常，异常信息：{}", e.getMessage());
		}
		long endTime = System.currentTimeMillis();
		log.info("导出excel数据运行时间：" + (endTime - startTime) + "ms");
		return filePath;
	}

	public List<JimuReport> excelQuery(String reportType, String name){
		JimuReport var7 = new JimuReport();


		if (ObjectUtil.isNotEmpty(reportType)) {
			var7.setType(reportType);
		}else {
			var7.setType("datainfo");
		}

		if (ObjectUtil.isNotEmpty(name)) {
			var7.setName("%" + name + "%");
		}

		var7.setDelFlag(org.jeecg.modules.jmreport.common.constant.a.b);
		var7.setTemplate(org.jeecg.modules.jmreport.common.constant.c.e);
		List<JimuReport> list = customerReportMapper.getList(reportType, name);
//		JmPage resPage = org.jeecg.modules.jmreport.desreport.util.d.a(page);
		return list;
	}

	@Override
	public boolean file(String filePath) {
		boolean exist = FileUtil.exist(filePath);
		if(exist){
			return FileUtil.del(filePath);
		}
		return true;
	}

	@Override
	public R<String> fileDownHandle(ConfReportTaskInfo confReportTaskInfo) {
		JSONObject jsonObject = new JSONObject();
		JSONObject queryParam = new JSONObject();
		jsonObject.put("excelConfigId", confReportTaskInfo.getReportTemplateId());
		queryParam.put("startTime", confReportTaskInfo.getReportQueryStartTime());
		queryParam.put("endTime", confReportTaskInfo.getReportQueryEndTime());
		queryParam.put("endTime", confReportTaskInfo.getReportQueryEndTime());
		jsonObject.put("queryParam", queryParam);
		String reportFileName = confReportTaskInfo.getReportFileName();
		if(ObjectUtil.isNotEmpty(reportFileName) && reportFileName.contains("${toady()}")){
			reportFileName.replace("${toady()}",DateUtil.today()) ;
		}
		jsonObject.put("fileName", confReportTaskInfo.getReportFileName());
		try {
			String filePath = exportAllExcelStream(jsonObject);
			return R.ok(filePath);
		}catch (Exception e){
			log.error("导出文件出错，错误信息：{}", e.getMessage());
			R.failed(e.getMessage());
		}
		return R.ok();
	}

	@Override
	public String getPreviewUrl(String reportTemplateId) {
		JimuReportShare share = this.jurisdictionService.selectJurisdiction(reportTemplateId);
		if (null != share) {
			share = this.jurisdictionService.compareToDate(share);
		}
		String previewUrl = share.getPreviewUrl();
		return previewUrl;
	}

	/**
	 * 根据配置给值
	 *
	 * @param defaultJson 默认值
	 * @param configJson  配置值
	 */
	private void setParamValue(JSONObject defaultJson, JSONObject configJson) {
		Set<String> keys = defaultJson.keySet();
		for (String key : keys) {
			if (configJson.containsKey(key)) {
				defaultJson.put(key, configJson.get(key));
			}
		}

	}

	/**
	 * 检查文件存放路径是否存在，以及路临时文件清理
	 */
	public void checkDocsBasePathAndTmpDocs() {
		File file = new File(basePath);
		if (!file.exists()) {
			file.mkdirs();
		}
	}
}
